﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Lincolnwood.Foundation.Scheduling.Data;

namespace Lincolnwood.Foundation.Scheduling
{
    public class SchedulingService
    {
        IEventsRepository _eventsRepository;
        IScheduleRepository _scheduleRepository;
        

        public SchedulingService(IScheduleRepository scheduleRepository, IEventsRepository eventsRepository)
        {
            _scheduleRepository = scheduleRepository;
            _eventsRepository = eventsRepository;
        }

        public Schedule CreateSchedule(Account account, string name)
        {
            Schedule newSchedule = new Schedule(name);
            _scheduleRepository.Add(newSchedule);
            return newSchedule;
        }

        public RecurrableEventDefinition CreateEvent(Schedule schedule, string name, string description, DateTime startTime, DateTime endTime)
        {
            RecurrableEventDefinition eventDefinition = new RecurrableEventDefinition(schedule.Id, name, description, startTime, endTime);
            return eventDefinition;
        }

        public void ScheduleEvent(RecurrableEventDefinition testEventDefinition)
        {
            _eventsRepository.Add(testEventDefinition);
        }

        public void UnscheduleEvent(Guid eventDefinitionId)
        {
            _eventsRepository.RemoveById(eventDefinitionId);
        }

        public RecurrableEventDefinition GetEventDefinitionById(Guid eventDefinitionId)
        {
            return _eventsRepository.FindById(eventDefinitionId);
        }

        public List<IEventInstance> GetEvents(DateTime beginDate, DateTime endDate)
        {
            IEnumerable<RecurrableEventDefinition> eventDefinitions =  _eventsRepository.GetEventDefinitionsInRange(beginDate, endDate);
            List<IEventInstance> expandedEvents = new List<IEventInstance>();
            foreach(RecurrableEventDefinition eventDefinition in eventDefinitions)
            {
                expandedEvents.AddRange(eventDefinition.ExpandInstances(beginDate, endDate));
            }

            return expandedEvents;
        }
                
    }
}
